"use strict";
const ctrl = {};
const xml = require('../../lib/xmlTools');
const wxMessage = require('../../lib/wxMessage');
const parseXmlBody = async (ctx, next) => {
    if (ctx.method === 'POST' && ctx.is('text/xml')) {
        let promise = new Promise(function (resolve, reject) {
            let buf = '';
            ctx.req.setEncoding('utf8');
            ctx.req.on('data', (chunk) => {
                buf += chunk
            });
            ctx.req.on('end', () => {
                xml.xmlToJson(buf)
                    .then(resolve)
                    .catch(reject)
            })
        });
        await promise.then((result) => {
            ctx.req.body = result
        }).catch((e) => {
            e.status = 400
        });
        next()
    } else {
        await next()
    }
};
ctrl.checkSignature = async (ctx) => {
    console.log(ctx.query);
    ctx.status = 200;
    ctx.body = ctx.query.echostr;
};
ctrl.receive = async (ctx) => {
    let xml = ctx.req.body.xml;
    let resBody = await wxMessage.dealMessage(xml);
    ctx.status = 200;
    ctx.body = resBody ? resBody : "success";
};
module.exports = (_, pre = '/wx') =>{
    _.get(pre, ctrl.checkSignature);
    _.post(pre, parseXmlBody, ctrl.receive);
};